<?php


namespace app\partneradmin\controller;


use app\admin\model\CustomerServiceAccount;
use app\admin\model\MemberConfig;
use app\api\model\UserMortgageInfo;
use app\partneradmin\model\AppBase;
use app\common\controller\partneradmin\Base;
use app\partneradmin\model\CustomerServiceAccountMiddle;
use app\partneradmin\model\UserInfo;

class User extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\User;
    }

    /**
     * 获取用户状态
     */
    public function getUserStatus()
    {
        $data = [
            '1' => '新用户',
            '2' => '点击借款期数（审核前）',
            '3' => '选择借款额度（审核前）',
            '4' => '提交贷款申请（审核前）',
            '5' => '提交基本信息',
            '6' => '提交工作信息',
            '7' => '提交银行信息',
            '8' => '提交活体认证',
            '20' => '审核中',
            '21' => '审核通过，获取可借贷额度',
            '22' => '点击借款期数（审核通过）',
            '23' => '选择借款额度（审核通过）',
            '24' => '提交贷款申请（审核通过）',
            '25' => '提交贷款_打款中',
            '26' => '提交贷款_打款成功 ',
            '27' => '提交贷款_打款失败',
            '28' => '还款',
            '29' => '还款_处理中',
            '30' => '还款_成功',
            '31' => '还款_失败',
            '32' => '提现',
            '33' => '提现_处理中',
            '34' => '提现_成功',
            '35' => '提现_失败',
        ];
        $list = [];
        foreach ($data as $key => $val) {
            $info = [
                'current_status' => $key,
                'content' => $val
            ];
            $list[] = $info;
        }
        $this->success('状态列表', '', ['list' => $list]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $mobile = $this->request->post('mobile', '');
            $startOpenTime = $this->request->post('start_open_time', '');
            $endOpenTime = $this->request->post('end_open_time', '');
            $startJoinTime = $this->request->post('start_join_time', '');
            $endJoinTime = $this->request->post('end_join_time', '');
            $status = $this->request->post('status', '');
            $current_status = $this->request->post('current_status', '');
            $source = $this->request->post('source', '');
            $app_base_id = $this->request->post('app_base_id', '');
            $is_check_kf_switch = $this->request->post('is_check_kf_switch', '');
            $customer_service_personnel_name = $this->request->post('customer_service_personnel_name', '');
            $customer_service_account_name = $this->request->post('customer_service_account_name', '');
            $country_config_id = $this->request->post('country_config_id', '');
            $member_config_id = $this->request->post('member_config_id', '');
            if ($member_config_id != '') {
                $where['member_config_id'] = $member_config_id;
            }
            if ($country_config_id != '') {
                $where['country_config_id'] = $country_config_id;
            }

            $where['is_del'] = 0;
            $adminCustomerServiceInfo = $this->getCustomerServiceInfo(trim($customer_service_personnel_name), trim($customer_service_account_name));

            if (empty($adminCustomerServiceInfo['middle_ids'])) {
                $resData = [
                    'total' => 0,
                    'list' => [],
                    'totalPage' => 0
                ];
                $this->success('列表', '', $resData);
            }
            $where['customer_service_account_middle_id'] = ['in', $adminCustomerServiceInfo['middle_ids']];
//            switch ($this->admin['rule']) {
//
//                case 3:
//                    $where['customer_service_account_middle_id'] = ['in', $adminCustomerServiceInfo['middle_ids']];
//                    break;
//                case 1:
//                case 2:
//                    $where['customer_service_account_middle_id'] = $adminCustomerServiceInfo['middle_id'];
//                    break;
//            }
            //筛选手机号（模糊）
            if ($mobile != '') {
                $where['mobile'] = ['like', '%' . $mobile . '%'];
            }
            //最后一次打开时间筛选（范围）
            if ($startOpenTime != '' && $endOpenTime != '') {
                $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
                $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
                $where['logintime'] = ['between', [$startOpenTime, $endOpenTime]];
            }
            //加入时间筛选（范围）
            if ($startJoinTime != '' && $endJoinTime != '') {
                $startJoinTime = strtotime($startJoinTime . '00:00:00');//格式化开始时间
                $endJoinTime = strtotime($endJoinTime . '23:59:59');//格式化结束时间
                $where['jointime'] = ['between', [$startJoinTime, $endJoinTime]];
            }
            //筛选状态（精准） 
            if ($status != '') {
                $where['status'] = $status;
            }
            if ($current_status != '') {
                $where['current_status'] = $current_status;
            }
            //筛选来源（精准）
            if ($source != '') {
                $where['source'] = $source;
            }
            //筛选app_id（模糊）
            if ($app_base_id != '') {
                $where['app_base_id'] = $app_base_id;
            }
            //筛选is_check_kf_switch
            if ($is_check_kf_switch != '') {
                $where['is_check_kf_switch'] = $is_check_kf_switch;
            }
            $field = [
                'id',
                'username',
                'mobile',
                'avatar',
                'age',
                'prevtime',
                'logintime',
                'loginip',
                'loginip',
                'joinip',
                'jointime',
                'quota',
                'status',
                'current_status',
                'source',
                'app_base_id',
                'create_time',
                'is_check_kf_switch',
                'customer_service_account_middle_id',
                'member_config_id',
                'is_show',
                'is_show_contact_kf',
                'is_wallet_show',
                'is_wallet_activation',
                'wallet_balance',
                'bad_bank_num',
                'withdrawal_password_show',
                'country_config_id',
                'diff_time',
                'channel',
                'is_install_unit',
                'is_pay_status',
            ];
            $list = $this->model
                ->field(implode(',', $field))
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            if (!empty($list)) {
                $list = $this->model->formatUserData($list);
            }
            //获取所有会员配置列表
            $memberConfigList = MemberConfig::getMemberConfigAll();
            $memberConfigList = array_column($memberConfigList, null, 'id');
            //取出所有应用列表
            $appBaseList = AppBase::select()->toArray();
            $appBaseList = array_column($appBaseList, null, 'id');
            //取出所有国家列表
            $countryConfigList = \app\admin\model\CountryConfig::select()->toArray();
            $countryConfigList = array_column($countryConfigList, null, 'id');
            foreach ($list as $key => $value) {
                $value['member_name'] = empty($memberConfigList[$value['member_config_id']]) ? "非会员" : $memberConfigList[$value['member_config_id']]['name'];
                $value['app_base_title'] = empty($appBaseList[$value['app_base_id']]) ? '' : $appBaseList[$value['app_base_id']]['title'];
                $value['country_name'] = empty($countryConfigList[$value['country_config_id']]) ? '' : $countryConfigList[$value['country_config_id']]['name'];
                //钱包余额 取贷款成功的总金额
                $balance = \app\partneradmin\model\LoanOrder::where([
                    'user_id' => $value['id'],
                    'status' => 3
                ])
                    ->sum('amount_money');
                //计算累加到额度的支付页面金额
                $payViewBalance = \app\partneradmin\model\PayView::where([
                    'is_quota' => 1,
//                    'is_abandoned' => 0,
                    'status' => 3,
                    'user_id' => $value['id'],
                ])->sum('amount_money');
                $balance = $balance + $payViewBalance;
                //减去提现总金额
                $withdrawalMoney = \app\partneradmin\model\WithdrawalOrder::where([
                    'user_id' => $value['id'],
                    'status' => ['neq', 2]
                ])
                    ->sum('amount_money');
                $balance = $balance - $withdrawalMoney;
                $value['wallet_balance'] = $balance + $value['wallet_balance'];
                //取用户最后一条贷款订单的金额
                $lastLoanOrderInfo = \app\partneradmin\model\LoanOrder::field('amount_money')->where([
                    'user_id' => $value['id']
                ])
                    ->order('id', 'desc')
                    ->find();
                $value['quota'] = empty($lastLoanOrderInfo) ? 0 : $lastLoanOrderInfo['amount_money'];
                //检查这个手机号在其他app是否注册过
                $oldWhere = [
                    'username' => $value['username'],
                    'app_base_id' => ['neq', $value['app_base_id']]
                ];
                $value['old_status'] = 1;
                $oldUser = \app\admin\model\User::field('id,is_pay')->where($oldWhere)->select()->toArray();
                if (!empty($oldUser)) {
                    $value['old_status'] = 2;
                    foreach ($oldUser as $v) {
                        if ($v['is_pay'] == 1) {
                            $value['old_status'] = 3;
                        }
                    }
                }
                $list[$key] = $value;
            }
            $list = array_values($list);
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }
    /**
     * 根据用户  获取用户在其他app支付的金额
     */
    public function getOldAppPayMoney($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        $list = [];
        //检查这个手机号在其他app是否注册过
        $oldWhere = [
            'username' => $row['username'],
            'app_base_id' => ['neq', $row['app_base_id']]
        ];
        $oldUser = \app\admin\model\User::field('id,is_pay,app_base_id,create_time')->where($oldWhere)->select()->toArray();
        //如果在其他app注册过  则直接获取
        if (empty($oldUser)) {
            $this->success('列表', '', $list);
        }
        //取出所有应用列表
        $appBaseList = AppBase::select()->toArray();
        $appBaseList = array_column($appBaseList, null, 'id');
        foreach ($oldUser as $value) {
            $info = [];
            //app名字
            $info['app_base_title'] = empty($appBaseList[$value['app_base_id']]) ? '' : $appBaseList[$value['app_base_id']]['title'];
            //注册金额
            $info['create_time'] = $value['create_time'];
            //是否付费
            $info['is_pay'] = $value['is_pay'];
            //付费金额
            $info['pay_money'] = 0;
            if ($value['is_pay'] == 1) {
                //获取用户付费总金额
                $payWhere = [
                    'user_id' => $value['id'],
                    'status' => 3
                ];

                $info['pay_money'] = \app\admin\model\PayView::where($payWhere)->sum('amount_money');
            }
            $list[] = $info;
        }
        $this->success('列表', '', $list);
    }

    /**
     * 获取用户钱包余额 提现密码
     */
    public function getWalletBalance($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        //钱包余额 取贷款成功的总金额
        $balance = \app\admin\model\LoanOrder::where([
            'user_id' => $ids,
            'status' => 3
        ])
            ->sum('amount_money');
        //计算累加到额度的支付页面金额
        $payViewBalance = \app\admin\model\PayView::where([
            'is_quota' => 1,
//            'is_abandoned' => 0,
            'status' => 3,
            'user_id' => $ids,
        ])->sum('amount_money');
        $balance = $balance + $payViewBalance;
        //减去提现总金额
        $withdrawalMoney = \app\admin\model\WithdrawalOrder::where([
            'user_id' => $ids,
            'status' => ['neq', 2]
        ])
            ->sum('amount_money');
        $balance = $balance - $withdrawalMoney;
        //加上钱包剩余余额
        $balance = $balance + $row['wallet_balance'];
        $info['id'] = $row['id'];
        $info['wallet_balance'] = $balance;
        $info['withdrawal_password_show'] = $row['withdrawal_password_show'];
        $info['is_wallet_activation'] = $row['is_wallet_activation'];
        $info['is_wallet_show'] = $row['is_wallet_show'];
        $this->success('获取成功', '', $info);
    }

    /**
     * 修改钱包余额
     */
    public function editWalletBalance($ids)
    {
        if ($this->admin['rule'] == 3) {
            $this->error('非客服不可操作!');
        }
        $row = $this->model->get($ids);
        $params = $this->request->post("");
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        $params['wallet_balance'] = $this->request->post('wallet_balance', '');
        if ($params['wallet_balance'] == '') {
            $this->error('钱包余额不能为空!');
        }
        if (!empty($params['withdrawal_password_show'])) {
            $row->withdrawal_password = md5(md5($params['withdrawal_password_show']) . $row['salt']);
            $row->withdrawal_password_show = $params['withdrawal_password_show'];
        }
        //钱包余额 取贷款成功的总金额
        $balance = \app\admin\model\LoanOrder::where([
            'user_id' => $ids,
            'status' => 3
        ])
            ->sum('amount_money');
        //计算累加到额度的支付页面金额
        $payViewBalance = \app\admin\model\PayView::where([
            'is_quota' => 1,
            'status' => 3,
            'user_id' => $ids,
        ])->sum('amount_money');
        $balance = $balance + $payViewBalance;
        //减去提现总金额
        $withdrawalMoney = \app\admin\model\WithdrawalOrder::where([
            'user_id' => $ids,
            'status' => ['neq', 2]
        ])
            ->sum('amount_money');
        $balance = $balance - $withdrawalMoney;
        $row->wallet_balance = $params['wallet_balance'] - $balance;
        $result = $row->save();
        if ($result !== false) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 禁止新增
     */
    public function add()
    {
        $this->error('禁止新增');
        //   parent::add(); // TODO: Change the autogenerated stub
    }

    /**
     * 查看用户提交信息
     */
    public function getUserInfoByUserId($ids)
    {
        $typeArr = [
            '34' => 1,
            '35' => 1,
            '36' => 1,
        ];
        $type = $this->request->post("type", 34);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if (empty($typeArr[$type])) {
            $this->error('非法type!');
        }
        switch ($type) {
            case 34:
            case 35:
                $info = UserInfo::where([
                    'user_id' => $ids,
                    'type' => $type
                ])->find();
                if (empty($info)) {
                    $this->error('当前用户未提交该信息!');
                }
                $data = json_decode($info['info_json'], true);
                $data['id'] = $info['id'];
                $this->success('获取成功', '', $data);
                break;
            case 36:
                $list = UserInfo::where([
                    'user_id' => $ids,
                    'type' => $type
                ])->order('id', 'asc')->select();
                if (empty($list)) {
                    $this->error('当前用户未提交该信息!');
                }
                $data = [];
                foreach ($list as $value) {
                    $info = json_decode($value['info_json'], true);
                    $info['bad_bank_num'] = $row['bad_bank_num'];
                    $info['id'] = $value['id'];
                    $data[] = $info;
                }
                $this->success('获取成功', '', ['list' => $data]);
                break;
        }
    }

    /**
     * 编辑用户提交的信息
     */
    public function updateUserInfo($ids = null)
    {
        if ($this->admin['rule'] == 3) {
            $this->error('非客服不可操作!');
        }
        $row = \app\admin\model\UserInfo::get($ids);
        $params = $this->request->post("");
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if (!empty($params['bad_bank_num'])) {
            $user = $this->model->get($row['user_id']);
            $user->save(['bad_bank_num' => $params['bad_bank_num']]);
        }
        unset($params['ids']);
        $updateData = [
            'id' => $ids,
            'info_json' => json_encode($params)
        ];
        $result = $row->save($updateData);
        if ($result !== false) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 数据的设置操作, 目前有  开关  是否默认  状态
     */
    public function setup($ids = "")
    {
        if ($this->admin['rule'] == 3) {
            $this->error('非客服不可操作!');
        }
        $type = $this->request->post("type");
        $val = $this->request->post("val");
        $field = $type;
        switch ($type) {
            case 'switch':
            case 'is_show':
            case 'status':

            case 'is_show_contact_kf':
            case 'is_wallet_show':
            case 'is_pay_status':
            case 'is_wallet_activation':
                $data[$field] = $val;
                $where['id'] = ['in', $ids];
                break;
            case 'is_check_kf_switch':
                if ($val == 0) {
                    $val = 1;
                }
                $data[$field] = $val;
                $where['id'] = ['in', $ids];
                break;
            case 'is_default':
                if ($val == 1) {
                    $oldwhere['id'] = ['neq', $ids];
                    $oldwhere['is_default'] = 1;
                    $this->model->update(['is_default' => 0], $oldwhere);
                    $data[$field] = $val;
                    $where['id'] = $ids;
                }
                break;
            default:
                $this->error('不存在的业务');
                break;
        }
        if ($type == 'is_wallet_show' && $val == 1) {
            //打开我的钱包的时候  如果没有提现订单 则生成一条金额为0的提现订单
            $WithdrawalorderNum = \app\admin\model\WithdrawalOrder::where(['user_id' => $ids, 'amount_money' => 0])->count('id');
            if (empty($WithdrawalorderNum)) {
                $info = \app\admin\model\User::get($ids);
                //查找客服id
                $customer_service_account_middle = \app\partneradmin\model\CustomerServiceAccountMiddle::get($info['customer_service_account_middle_id']);
                $customer_service_account = CustomerServiceAccount::get($customer_service_account_middle['customer_service_account_id']);
                $setWithdrawalOrderData = [
                    'cash_out_num' => createTradeNo(),
                    'user_id' => $ids,
                    'amount_money' => 0,
                    'source' => 1,
                    'app_base_id' => $info['app_base_id'],
                    'status' => 1,
                    'partner_id' => $customer_service_account['partner_id'],
                    'customer_service_group_id' => $customer_service_account['customer_service_group_id'],
                    'customer_service_personnel_id' => $customer_service_account['customer_service_personnel_id'],
                ];
                //创建还款订单
                \app\partneradmin\model\WithdrawalOrder::create($setWithdrawalOrderData);
            }
        }
        $this->model->update($data, $where);
        $this->success('操作成功');
    }
    /**
     * 查看用户提交的抵押信息
     */
    public function getUserMortgageInfo($ids = null)
    {
        if (empty($ids)) {
            $this->error('查询失败,无用户id');
        }
        $row = $this->model->get($ids);
        if (empty($ids)) {
            $this->error('查询失败,无用户');
        }
        $info = UserMortgageInfo::get(['user_id' => $ids]);
        $type_array = [
            1 => '抵押贷款',
            2 => '无抵押信用的贷款',
        ];
        $group_arr = [
            0 => '无抵押',
            1 => '房产',
            2 => '汽车',
            3 => '债券'
        ];
        if (!empty($info)) {
            $info['type_name'] = $type_array[$info['type']];
            $info['group_name'] = $group_arr[$info['group_type']];
        }
        $this->success('成功', '',$info);
    }

}